package p.ithorns.tools.excel.convert;

import cn.idev.excel.converters.Converter;
import cn.idev.excel.enums.CellDataTypeEnum;
import cn.idev.excel.metadata.GlobalConfiguration;
import cn.idev.excel.metadata.data.ReadCellData;
import cn.idev.excel.metadata.data.WriteCellData;
import cn.idev.excel.metadata.property.ExcelContentProperty;
import org.apache.poi.ss.usermodel.DateUtil;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;

/**
 * LocalDateTimeStringConverter
 * <p>
 * EasyExcel String转LocalDateTime
 *
 * @author HtL
 * @date 2024/7/16 16:37
 * @since 1.0.0
 */
public class LocalDateTimeConverter implements Converter<LocalDateTime> {

    /**
     * 日期时间格式
     */
    private final static DateTimeFormatter DATE_TIME_PATTERN = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");


    @Override
    public Class<?> supportJavaTypeKey() {
        return LocalDateTime.class;
    }

    @Override
    public CellDataTypeEnum supportExcelTypeKey() {
        return CellDataTypeEnum.STRING;
    }


    @Override
    public LocalDateTime convertToJavaData(ReadCellData<?> cellData, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) throws Exception {
        CellDataTypeEnum type = cellData.getType();
        if (type.equals(CellDataTypeEnum.NUMBER)) {
            // 转换成LocalDateTime
            BigDecimal numberValue = cellData.getNumberValue();
            Date date = DateUtil.getJavaDate(numberValue.doubleValue());
            return DateUtil.toLocalDateTime(date);
        }

        if (type.equals(CellDataTypeEnum.STRING)) {
            return LocalDateTime.parse(cellData.getStringValue(), DATE_TIME_PATTERN);
        }

        throw new UnsupportedOperationException("未知日期格式内容.");
    }

    @Override
    public WriteCellData<?> convertToExcelData(LocalDateTime value, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) throws Exception {
        String datetime = DATE_TIME_PATTERN.format(value);
        return new WriteCellData<>(datetime);
    }

}